#include "songitem.h"
#include "albumwidget.h"
#include <synchapi.h>

SongItem::SongItem(QWidget *parent)
    : QWidget{parent},fixedwidth{215}
{
    player=nullptr;
    songerslabel=new AdaptiveMultiLabel(this);
    albumlabel=new AdaptiveMultiLabel(this);
    titlelabel=new AdaptiveMultiLabel(this);
    orderlabel=new QLabel(this);
    durationlabel=new QLabel(this);
    picturelabel=new QLabel(this);
    likebtn=new QPushButton(this);
    color=QColor("#f7f9fc");
    checkbox=new QCheckBox(this);

    checkbox->setStyleSheet("background:transparent;");

    orderlabel->setFixedSize(25,orderlabel->height());
    orderlabel->setStyleSheet("QLabel{"
                    "color:black;"
                    "background:transparent;"
                    "}");

    picturelabel->setFixedSize(40,40);
    picturelabel->setStyleSheet("QLabel{"
                                "border-radius:1px;"
                                "}");

    titlelabel->setAlignment(Qt::AlignLeft);
    titlelabel->setFont(QFont("Microsoft YaHei",10));
    titlelabel->setStyleSheet("QLabel{"
                              "color:black;"
                              "background:transparent;"
                              "}");

    songerslabel->setAlignment(Qt::AlignLeft);
    songerslabel->setFont(QFont("Microsoft YaHei",9));
    songerslabel->setStyleSheet("QLabel{"
                                "color:grey;"
                                "background:transparent;"
                                "}");

    albumlabel->setFont(QFont("Microsoft YaHei",10,30));
    albumlabel->setStyleSheet("QLabel{"
                              "color:grey;"
                              "background:transparent;"
                              "}");

    likebtn->setFixedSize(30,30);
    likebtn->setIconSize(QSize(20,20));
    likebtn->setStyleSheet("background:transparent");

    durationlabel->setFixedSize(40,40);
    durationlabel->setStyleSheet("QLabel{"
                    "color:grey;"
                    "background:transparent;"
                    "}");

    checkbox->setGeometry(10,15,25,25);
    orderlabel->setGeometry(10,15,25,25);
    picturelabel->setGeometry(45,10,40,40);
    titlelabel->setGeometry(95,0,120,30);
    songerslabel->setGeometry(95,30,120,30);
    albumlabel->setGeometry(215,15,120,30);
    likebtn->setGeometry(width()-90,15,30,30);
    durationlabel->setGeometry(width()-50,10,40,40);

    checkbox->setHidden(true);

    connect(likebtn,&QPushButton::clicked,this,&SongItem::onButtonClicked);
    setAttribute(Qt::WA_Hover);//开启悬浮事件
    setFixedHeight(60);
    setMinimumWidth(800);
    SetNormal();
    SetNotChosen();
    SetCheckMode(false);
}

void SongItem::SetPicture(const QByteArray&bytearray)
{
    QImage image(bytearray);
    SetPicture(image);
}

void SongItem::SetPicture(const QString&filepath)
{
    QImage image(filepath);
    SetPicture(image);
}

void SongItem::SetPicture(const QImage&image)
{
    QPixmap pixmap=QPixmap::fromImage(image);
    auto t=paintPictureRoundRect(pixmap.scaled(picturelabel->size(),Qt::KeepAspectRatio,Qt::SmoothTransformation),5);
    picturelabel->setPixmap(t);
}

void SongItem::SetChosen()
{
    ischosen=true;
    color=QColor("#ffffff");
    repaint();
}

void SongItem::SetNotChosen()
{
    ischosen=false;
    color=QColor("#f7f9fc");
    repaint();
}

void SongItem::SetLikeMode(bool flag)
{
    if(flag)
    {
        likebtn->show();
    }
    else
    {
        likebtn->hide();
    }
}

void SongItem::SetLike()
{
    islike=true;
    likebtn->setIcon(QIcon(":/icon/like.png"));
    emit like();
}

void SongItem::SetNormal()
{
    islike=false;
    likebtn->setIcon(QIcon(":/icon/normal.png"));
    emit dislike();
}

void SongItem::SetCheckMode(bool flag)
{
    if(flag==true)
    {
        orderlabel->hide();
        checkbox->show();

    }
    else
    {
        orderlabel->show();
        checkbox->hide();
    }
}

void SongItem::SetCheck(bool flag)
{
    if(flag)
        checkbox->setCheckState(Qt::CheckState::Checked);
    else
        checkbox->setCheckState(Qt::CheckState::Unchecked);
}

void SongItem::SetPlayMode(bool flag)
{
    if(flag)
    {
        titlelabel->setStyleSheet("QLabel{color:#ea3e3e;background:transparent;}");
        songerslabel->setStyleSheet("QLabel{color:#ea3e3e;background:transparent;}");
    }
    else
    {
        titlelabel->setStyleSheet("QLabel{"
                                  "color:black;"
                                  "background:transparent;"
                                  "}");
        songerslabel->setStyleSheet("QLabel{"
                                    "color:grey;"
                                    "background:transparent;"
                                    "}");
    }
}

void SongItem::paintEvent(QPaintEvent*e)
{
    QWidget::paintEvent(e);
    QPainter painter(this);
    painter.setBrush(color);
    painter.setPen(Qt::NoPen);
    painter.drawRoundedRect(rect(),10,10);
}

void SongItem::mousePressEvent(QMouseEvent*e)
{
    QWidget::mousePressEvent(e);
    if(e->button()==Qt::RightButton)
    {
        SetChosen();
        QPoint point=mapToGlobal(e->pos());
        emit mouseRightPress(point);
    }
    else if(e->button()==Qt::LeftButton)
    {
        if(ischosen)//如果已经选中，就发出双击
        {
            int duration=clicktime.msecsTo(QTime::currentTime());
            if (duration < QApplication::doubleClickInterval())//时间间隔小于双击时间
            {
                emit doubleClicked();
            }

        }
        clicktime=QTime::currentTime();//获取点击时间，用于判断双击
        SetChosen();
        emit chosen();
    }
}

void SongItem::resizeEvent(QResizeEvent*e)
{
    QWidget::resizeEvent(e);
    likebtn->setGeometry(width()-100,15,30,30);
    durationlabel->setGeometry(width()-50,10,40,40);


    qint32 newwidth=(e->size().width()-fixedwidth)>>1;
    titlelabel->setGeometry(95,10,newwidth,20);
    songerslabel->setGeometry(95,30,newwidth,20);
    albumlabel->setGeometry(105+newwidth,15,newwidth,30);
    qDebug()<<newwidth;
}

bool SongItem::event(QEvent*e)
{
    if(e->type()==QEvent::HoverEnter)
    {
        color=QColor("#ffffff");
        update();
        //qDebug()<<"orderlabel:"<<orderlabel->size()<<"picturelabel:"<<picturelabel->size()<<"likebtn:"<<likebtn->size()<<"durationlabel:"<<durationlabel->size();
        //qDebug()<<"titlelabel:"<<titlelabel->geometry()<<"songerslabel:"<<songerslabel->geometry()<<"albumlabel:"<<albumlabel->geometry();
    }
    else if(e->type()==QEvent::HoverLeave&&!ischosen)
    {
        color=QColor("#f7f9fc");
        update();
    }
    return QWidget::event(e);
}

void SongItem::onButtonClicked()
{
    if(islike)
        SetNormal();
    else
        SetLike();
}

QPixmap SongItem::paintPictureRoundRect(const QPixmap&pixmap, qint32 radius)
{
    QPixmap result(pixmap.size());
    result.fill(Qt::transparent); // 填充透明背景

    QPainter painter(&result);
    painter.setRenderHint(QPainter::Antialiasing); // 抗锯齿

    // 创建圆角路径
    QPainterPath path;
    path.addRoundedRect(0, 0, pixmap.width(), pixmap.height(), radius, radius);

    // 裁剪图片
    painter.setClipPath(path);
    painter.drawPixmap(0, 0, pixmap);
    return result;
}

void SongItem::SetSource(const QUrl&url)
{
    player=new QMediaPlayer;
    mp3filepath=url;
    connect(player,&QMediaPlayer::metaDataChanged,this,&SongItem::onMetaDataChanged);
    player->setSource(url);
    player->play();
    player->pause();
}

SongItem*  SongItem::FromLocalFile(const QString&filepath)
{
    SongItem* ptr=new SongItem;
    ptr->SetSource(QUrl(filepath));
    ptr->SetNormal();
    return ptr;
}

SongItem* SongItem::FromJsonOBJect(const QJsonObject&obj)
{
    qint64 songid=obj["song_id"].toInt();

    SongItem* ptr=new SongItem;
    ptr->SetSongId(songid);
    ptr->SetSource(QUrl(QString("http://127.0.0.1:8080/songs/%1.mp3").arg(QString::number(songid))));

    return ptr;
}

SongItem* SongItem::FromUrl(const QUrl&url)
{
    SongItem* ptr=new SongItem;
    QString number=url.fileName().split('.')[0];
    qint64 songid=number.toInt();
    ptr->SetSongId(songid);
    ptr->SetSource(url);
    return ptr;
}

void SongItem::onMetaDataChanged()
{
    auto metadata=player->metaData();

    SetPicture(metadata[QMediaMetaData::ThumbnailImage].value<QImage>());
    SetSongName(metadata[QMediaMetaData::Title].value<QString>());
    SetSongers(metadata[QMediaMetaData::ContributingArtist].value<QStringList>());
    SetAlbum(metadata[QMediaMetaData::AlbumTitle].value<QString>());
    qint32 duration=metadata[QMediaMetaData::Duration].value<qint32>()/1000;
    SetDuration(duration/60,duration%60);

    if(orderlabel->text().toInt()==1)
    {
        emit updateAlbumPicture(metadata[QMediaMetaData::ThumbnailImage].value<QImage>());
    }

    delete player;
    emit metaDataReady();
}

void AdaptiveMultiLabel::SetStringList(const QStringList&strlist)
{
    if(strlist.isEmpty())
        return;
    QString str;
    //应对QMediaMetaData::ContributingArtist中全在一个QStringList的情况
    if(strlist.first().contains('/'))
    {
        str=strlist.first();
        mstrlist=str.split('/',Qt::SkipEmptyParts);
    }
    //应对不在一个QStringList的情况
    else
    {
        mstrlist=strlist;
        for(const auto&elem:strlist)
        {
            str+=elem+'/';
        }
        str.erase(str.end()-1,str.end());
    }
    AdaptiveLabel::setAdaptiveText(str);
}

void AdaptiveMultiLabel::setGeometry(qint32 x,qint32 y,qint32 width,qint32 height)
{
    QFontMetrics metrics(font());
    QRect rect=metrics.boundingRect(text());//获取文本全部显示所需要的长度
    if(rect.width()>width)
    {
        AdaptiveLabel::setGeometry(x,y,width,height);
        setFixedSize(width,height);
        AdaptiveLabel::setAdaptiveText(text());
    }
    else
    {
        AdaptiveLabel::setGeometry(x,y,rect.width()+1,height);
        setFixedSize(rect.width()+1,height);
        setText(text());
    }
}

void AdaptiveMultiLabel::mousePressEvent(QMouseEvent*e)
{
    QLabel::mousePressEvent(e);
    qDebug()<<FindString(e->position());
    emit clicked(FindString(e->position()));
}

QString AdaptiveMultiLabel::FindString(const QPointF&pointf)
{
    double width=pointf.x();
    QFontMetrics fm(font());
    for(int i=0;i<mstrlist.size();i++)
    {
        QRect rect=fm.boundingRect(mstrlist[i]);
        QRect symbolrect=fm.boundingRect('/');
        if(rect.width()>=width||i==mstrlist.size()-1)
            return mstrlist[i];
        else
            width=width-rect.width()-symbolrect.width();
    }
    return text();//如果都没找到，说明是没有SetStringList()
}

SongItemFirst::SongItemFirst(QWidget*parent):QWidget(parent),fixedwidth(205)
{
    orderlabel=new QLabel("#",this);
    titlelabel=new QLabel("标题",this);
    albumlabel=new QLabel("专辑",this);
    likelabel=new QLabel("喜欢",this);
    durationlabel=new QLabel("时长",this);
    checkbox=new QCheckBox(this);

    checkbox->setGeometry(10,10,25,20);
    orderlabel->setGeometry(10,10,25,20);
    titlelabel->setGeometry(45,0,40,40);
    albumlabel->setGeometry(215,0,120,40);
    likelabel->setGeometry(width()-100,0,30,40);
    durationlabel->setGeometry(width()-50,0,40,40);

    checkbox->setStyleSheet("background:transparent;");
    connect(checkbox,&QCheckBox::checkStateChanged,this,[this](Qt::CheckState state){
        if(state==Qt::Unchecked){
            emit selectAll(false);
        }else{
            emit selectAll(true);
        }
    });

    setFixedHeight(40);
    setMinimumWidth(800);
    SetCheckMode(false);
}

void SongItemFirst::SetCheckMode(bool flag)
{
    if(flag==true)
    {
        orderlabel->hide();
        checkbox->show();
        titlelabel->setText("全选");

    }
    else
    {
        orderlabel->show();
        checkbox->hide();
        titlelabel->setText("标题");
    }
}

void SongItemFirst::SetLikeMode(bool flag)
{
    if(flag)
    {
        likelabel->show();
    }
    else
    {
        likelabel->hide();
    }
}

void SongItemFirst::resizeEvent(QResizeEvent*e)
{
    QWidget::resizeEvent(e);
    likelabel->setGeometry(width()-100,15,30,30);
    durationlabel->setGeometry(width()-50,10,40,40);

    qint32 newwidth=(e->size().width()-fixedwidth)>>1;
    titlelabel->setGeometry(45,10,newwidth,20);
    albumlabel->setGeometry(105+newwidth,15,newwidth,30);
}
